<script setup lang="ts">
import type { Recordable } from '@vben/types';

import {h, ref } from 'vue';

import { Page, useVbenDrawer, type VbenFormProps } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';

import {message, Modal, Popconfirm, Space} from 'ant-design-vue';
import dayjs from 'dayjs';

import {
  useVbenVxeGrid,
  vxeCheckboxChecked,
  type VxeGridProps
} from '#/adapter/vxe-table';

import {
  financeDataExport,
  financeDataList,
  financeDataRemove,
  financeDataTrend,
  financeDataPredict,
  analyzeCorrelations
} from '#/api/system/financeData';
import type { FinanceDataForm } from '#/api/system/financeData/model';
import { commonDownloadExcel } from '#/utils/file/download';

import financeDataDrawer from './financeData-drawer.vue';
import { columns, querySchema } from './data';

const exTarColumns: VxeGridProps["columns"] = [
  {
    title: "",
    fixed: 'left',
    width: 60,
    slots: {
      header: ({ row }) => {
        const selectArr = tableApi.grid.getCheckboxRecords();
        const { visibleData } = tableApi.grid.getTableData();
        return [
          h("input", {
            type: "checkbox",
            checked: selectArr.length === visibleData.length,
            onChange: () => {
              // 如果全部选择的有的话，就清空
              if (selectArr.length === visibleData.length) {
                tableApi.grid.clearCheckboxRow();
              } else {
                tableApi.grid.toggleAllCheckboxRow();
              }
            },
             style: { height: '18px', width:'18px', cursor: "pointer", margin: 'auto', display: 'block' }
          }),
        ];
      },
      default: ({ row, rowIndex }) => {
        const isChecked = tableApi.grid.getCheckboxRecords().includes(row); // 用于控制复选框的选中状态
        const {pager} = tableApi.grid.getProxyInfo();
        const pageSize = pager.pageSize;
        const pageIndex = pager.currentPage;
        return [
          // 当复选框显示时，序号消失
          row.isHovered || isChecked
            ? h("input", {
                type: "checkbox",
                checked: tableApi.grid.getCheckboxRecords().includes(row), // 使用表格的多选记录
                onChange: () => {
                  tableApi.grid.toggleCheckboxRow(row); // 调用表格的多选方法
                },
                style: { height: '18px', width:'18px', cursor: "pointer", margin: 'auto', display: 'block' }
              })
            : h("span", (pageIndex - 1) * pageSize + rowIndex + 1), // 显示序号
        ];
      },
    },
  },
];

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 处理区间选择器RangePicker时间格式 将一个字段映射为两个字段 搜索/导出会用到
  // 不需要直接删除
  // fieldMappingTime: [
  //  [
  //    'createTime',
  //    ['params[beginTime]', 'params[endTime]'],
  //    ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
  //  ],
  // ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
    trigger: "cell",
  },
  columns: exTarColumns.concat(columns),
  border: true,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await financeDataList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    isHover: true,
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'system-financeData-index'
};

const checked = ref(false);
const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    cellMouseenter: (params) => {
      const { row } = params;
      row.isHovered = true;
    },
    cellMouseleave: (params) => {
      const { row } = params;
      row.isHovered = false;
    },
  }
});

const [FinanceDataDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: financeDataDrawer,
});

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

async function handleEdit(row: Required<FinanceDataForm>) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

async function handleDelete(row: Required<FinanceDataForm>) {
  await financeDataRemove(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<FinanceDataForm>) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await financeDataRemove(ids);
      await tableApi.query();
      checked.value = false;
    },
  });
}

function handleDownloadExcel() {
  commonDownloadExcel(financeDataExport, '财务数据数据', tableApi.formApi.form.values, {
    fieldMappingTime: formOptions.fieldMappingTime,
  });
}
async function handleTrendAnalysis() {
  const newVar = await financeDataTrend();
  // 假设 chartData 是 base64 编码的图片
  const base64Data = newVar.chartData;
  console.log(base64Data);
  downloadBase64Image(base64Data, '趋势分析.png');

}
async function handlePrediction() {
  const promise = await financeDataPredict();
  console.log(promise);
  downloadBase64Image(promise.predictionChart, '趋势预测.png');
  // message.info("暂未开放");
}

async function handleAnalyzeCorrelations() {
  message.info("暂未开放");
  // const promise = await analyzeCorrelations();
  // console.log(promise);
  // downloadBase64Image(promise.correlationChart, '财务指标相关性.png');
}

function downloadBase64Image(base64Data, filename = 'image.png') {
  // 去除 base64 前缀（如果有）
  const base64Prefix = 'data:image/png;base64,'; // 根据你的实际情况调整 MIME 类型
  const cleanedBase64 = base64Data.startsWith(base64Prefix)
      ? base64Data.slice(base64Prefix.length)
      : base64Data;

  // 将 base64 转换为二进制数据
  const binaryString = atob(cleanedBase64);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }

  // 创建 Blob 对象
  const blob = new Blob([bytes], { type: 'image/png' }); // 根据实际情况调整 MIME 类型

  // 创建下载链接并触发点击
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();

  // 清理
  setTimeout(() => {
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, 100);
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="财务数据列表">
      <template #toolbar-tools>
        <Space>
          <a-button
              @click="handleTrendAnalysis"
          >
            趋势分析
          </a-button>
          <a-button
              @click="handlePrediction"
          >
            趋势预测
          </a-button>
          <a-button
              @click="handleAnalyzeCorrelations"
          >
            分析财务指标相关性
          </a-button>
          <a-button
            v-access:code="['system:financeData:export']"
            @click="handleDownloadExcel"
          >
            {{ $t('pages.common.export') }}
          </a-button>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['system:financeData:remove']"
            @click="handleMultiDelete">
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['system:financeData:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['system:financeData:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['system:financeData:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <FinanceDataDrawer @reload="tableApi.query()" />
  </Page>
</template>
